package com.ls.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by summer on 2016/11/25.
 */
//@Configuration
//@MapperScan(basePackages = "com.ls.mapper", sqlSessionTemplateRef  = "sqlSessionTemplate")
public class DataSource1Config {

    @Bean(name = "datasourceSlave1")
    @ConfigurationProperties(prefix = "spring.datasource.slave1")
    public DataSource slave1DataSource() {
        return  new DruidDataSource();
    }

    @Bean(name = "datasource")
    public DataSource getDataSource(@Qualifier("datasourceMaster") DataSource dataSource1,@Qualifier("datasourceSlave1") DataSource dataSource2) {
        DynamicDataSource dataSource = new DynamicDataSource();
        Map<Object,Object> map = new HashMap<>();
        map.put("master",dataSource1);
        map.put("slave1",dataSource2);
        dataSource.setTargetDataSources(map);
        dataSource.setDefaultTargetDataSource(dataSource1);
        System.out.println("use multiDatasource 使用动态数据源");
        return dataSource;
    }

    @Primary
    @Bean(name = "datasourceMaster")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("datasourceMaster") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:/mybatis/mybatis-config.xml"));
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mybatis/mapper/**/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "transactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("datasourceMaster") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
